package mysql

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gen"
	"gorm.io/gorm"
	"gozero-demo/internal/model/dao/model"
	"gozero-demo/internal/model/dao/query"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type GoodsRepo struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGoodsRepo(ctx context.Context, sCtx *svc.ServiceContext) *GoodsRepo {
	return &GoodsRepo{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: sCtx,
	}
}

// 创建数据
func (r *GoodsRepo) CreateGoods(models *model.Goods) (*model.Goods, error) {
	m := r.svcCtx.Model.Goods
	err := m.WithContext(r.ctx).Debug().Create(models)
	if err != nil {
		logx.WithContext(r.ctx).Errorf("Failed to insert data: %v", err)
		return nil, err
	}
	return models, nil
}

// 更新数据
func (r *GoodsRepo) UpdateGoods(models *model.Goods, id int64) (gen.ResultInfo, error) {
	m := r.svcCtx.Model.Goods
	res, err := m.WithContext(r.ctx).Debug().Where(m.ID.Eq(id)).Updates(models)
	if err != nil {
		logx.WithContext(r.ctx).Errorf("Failed to update data: %v", err)
		return res, err
	}
	return res, nil
}

// 构建查询数据的条件
func (r *GoodsRepo) BuildQueryGoodsListCondition(req *types.GoodsListRequest) (query.IGoodsDo, error) {
	m := r.svcCtx.Model.Goods
	querys := m.WithContext(r.ctx).Debug().Where(m.IsDeleted.Eq(0))
	if req.Id > 0 {
		querys = querys.Where(m.ID.Eq(req.Id))
	}
	if req.Status > 0 {
		querys = querys.Where(m.Status.Eq(req.Status))
	}
	if req.GoodsName != "" {
		querys = querys.Where(m.GoodsName.Like("%" + req.GoodsName + "%"))
	}

	return querys, nil
}
func (r *GoodsRepo) GetGoodsList(req *types.GoodsListRequest) (list []*model.Goods, count int64, err error) {
	m := r.svcCtx.Model.Goods
	querys, err := r.BuildQueryGoodsListCondition(req)
	if err != nil {
		return nil, 0, err
	}

	limit := int(req.PageSize)
	offset := (int(req.Page) - 1) * limit
	res, count, err := querys.Order(m.ID.Desc()).FindByPage(offset, limit)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logx.WithContext(r.ctx).Errorf("Failed to get list: %v", err)
		return nil, 0, err
	}
	return res, count, nil
}
